import * as echarts from "echarts";
import { useEffect, useRef } from "react";
import { Theme } from "../../theme";

import defaultChartTheme from "../../theme/echarts/01-default.json";
import darkChartTheme from "../../theme/echarts/02-dark.json";
import yuqueChartTheme from "../../theme/echarts/03-yueque.json";

echarts.registerTheme("默认", defaultChartTheme);
echarts.registerTheme("暗黑", darkChartTheme);
echarts.registerTheme("语雀", yuqueChartTheme);

type Props = {
  theme: Theme;
  option: echarts.EChartsOption;
};

let chartInstances: any[] = [];

export function echartResizeByWindowResize(instance: echarts.ECharts) {
  chartInstances.push(instance);
  window.onresize = () => {
    chartInstances.forEach((i) => {
      i.resize();
    });
  };
}

export default function Chart(props: Props) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    let chartInstance: echarts.ECharts;
    if (ref.current) {
      chartInstance = echarts.init(ref.current, props.theme);
      chartInstance.setOption(props.option);
      echartResizeByWindowResize(chartInstance);
    }

    return () => {
      chartInstance.dispose();
    };
    // eslint-disable-next-line
  }, [props.theme, props.option]);

  return <div style={{ height: "100%" }} ref={ref}></div>;
}
